# -*- coding = utf-8 -*-
# @Time : 2022/1/13 23:14
# @Author : GHHHHHHHHH
# @File : mapInterface.py
# @Software : PyCharm
"""
1. 输入建筑图，提取为二值图
2. 商家只能提供超市货架平面图，则内置算法分区
3. 商家已有分好的区域，则直接输入
4. 加载历史缓存货架平面图
注意：2,3条提供的图片必须为二值图
"""

from generateMap import generateMap
from json_open_close import save_json, open_json
from regionalBlockMethod import RegionalBlockMethod
from floorFillColor import FloodFillImg
from getColors import initColors
import cv2 as cv

class Map(object):
    def __init__(self):
        super(Map, self).__init__()
        self.map = None
        self.mode = None
        self.maxChucks = 50
        self.colors = None
        self.cache = self.judgeCache()

    def judgeCache(self):
        if cv.imread("MapFile.png") is not None:
            return True
        return False

    def __bool__(self):
        if self.map is None:
            return False
        else:
            return True

    def __repr__(self):
        if bool(self.map):
            return f"A map with shape {self.map.shape}."
        else:
            return f"The map has not been initialized!"

    def setMapMode(self, mode):
        """
        :param mode: 0: 建筑图; 1: 二值货架图; 2:划分好区域的二值图
        :return: None
        """
        self.mode = mode

    def askForSure(self):
        """
        前端返回True/False
        :return:
        """
        print("模拟前端，输入Y使用缓存，否则不用")
        choice = input()
        if choice == "Y":
            return True
        else:
            return False

    def initMap(self, externalMap=None, saveMap=True, maxChuck=50):
        print("Initializing the Map......")
        if self.cache:
            """
                前端弹提示框，询问是否使用缓存图片
                    是               否
                            □下次不再提示
            """
            if self.askForSure():
                # 缓存图片
                self.map = cv.imread(".\\MapFile.png")
                if self.map is None:
                    raise ValueError("The map has not been Initialized!")
                self.colors = open_json("colors.json")
                self.colorAndMapSave(saveMap, self.map, True, self.colors)
                return
        if self.mode == 0:
            # 还没有写的建筑图纸功能
            pass
        elif self.mode == 1:
            # 超市货架图
            if externalMap is not None:
                self.getChuck(externalMap, True)
            else:
                raise ValueError("The externalMap couldn't be None!")
        elif self.mode == 2:
            # 商家提供的分区
            if externalMap is not None:
                xLength, yLength = externalMap.shape[0], externalMap.shape[1]
                for i in range(xLength):
                    for j in range(yLength):
                        if tuple(externalMap[i][j])[0] > 200 and tuple(externalMap[i][j])[1] > 200\
                                and tuple(externalMap[i][j])[2] > 200:
                            externalMap[i][j] = (255, 255, 255)
                        elif tuple(externalMap[i][j])[0] < 50 and tuple(externalMap[i][j])[1] < 50\
                                and tuple(externalMap[i][j])[2] < 50:
                            externalMap[i][j] = (0, 0, 0)
                fillTool = FloodFillImg(externalMap)
                self.map = fillTool.map
                self.colors = initColors(maxChuck)
            else:
                raise ValueError("The externalMap couldn't be None!")
        self.colorAndMapSave(saveMap, self.map, self.mode == 3, self.colors)

    def colorAndMapSave(self, flag1, _map, flag2, colors):
        if flag1:
            if _map is None:
                raise ValueError("The map couldn't be None!")
            cv.imwrite("MapFile.png", _map)
        if flag2:
            save_json("colors.json", colors)

    def getChuck(self, externalMap, flag):
        shelfBoundary = generateMap(externalMap, 800, 1000)
        regionTool = RegionalBlockMethod(shelfBoundary, self.maxChucks)
        self.map, self.colors = regionTool.mainCircle(flag)

    def setMaxChucks(self, maxChucks):
        self.maxChucks = maxChucks







